package com.controller;

import com.pojo.QueryVoucher;
import com.pojo.ShowVoucher;
import com.entry.Voucher;
import com.google.gson.Gson;
import com.service.VoucherService;
import com.service.impl.VoucherServiceImpl;

import com.entry.Financing;
import com.entry.Instituty;
import com.pojo.FinancingAmout;
import com.pojo.FinanceList;
import com.pojo.FinancingAnd;
import com.pojo.MyTicketDetail;
import com.service.FinancingService;
import com.service.UserService;
import com.service.impl.FinancingServiceImpl;
import com.entry.User;
import com.service.impl.UserServiceImpl;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

@WebServlet("/systerm/*")
public class DirectoryServlet extends HttpServlet {
    private FinancingService financingService = new FinancingServiceImpl();
    private FinancingAnd financingAnd = new FinancingAnd();
    private Instituty instituty = new Instituty();
    private Financing financing = new Financing();
    private UserService userService = new UserServiceImpl();
    private VoucherService voucherService = new VoucherServiceImpl();


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //0.处理乱码：
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        //1.获得请求路径
        String url = request.getRequestURI();
        String methodName = url.substring(url.lastIndexOf("/") + 1);
        Class cla = DirectoryServlet.class;
        try {
            Method method = cla.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(cla.newInstance(), request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

//    /**
//     * 查询
//     * @param request
//     * @param response
//     * @throws IOException
//     */
//    public void queryAllVoucher(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        QueryVoucher queryVoucher = new QueryVoucher();
//        ArrayList<ShowVoucher> vouchers = voucherService.select(queryVoucher);
//        System.out.println(vouchers);
//        Gson gson = new Gson();
//        response.getWriter().println(gson.toJson(vouchers));
//    }

    /**
     * 我的凭证表页面精查和全查功能需求
     * @param request
     * @param response
     * @throws IOException
     */
    public void queryByVoucher(HttpServletRequest request, HttpServletResponse response) throws IOException {
        QueryVoucher queryVoucher = new QueryVoucher();
        String no = request.getParameter("no");
        if (no != null && !no.isEmpty()) {
            queryVoucher.setNo(no);
        }
        String acquiring = request.getParameter("acquiring");
        if (acquiring != null && !acquiring.isEmpty()) {
            if (acquiring.equals("a")) {
                queryVoucher.setAcquiringEnterprise("百度科技有限公司");
            } else if (acquiring.equals("b")) {
                queryVoucher.setAcquiringEnterprise("京东集团");
            } else if (acquiring.equals("c")) {
                queryVoucher.setAcquiringEnterprise("小米");
            }
        }
        String open = request.getParameter("open");
        if (open != null && !open.isEmpty()) {
            if (open.equals("a")) {
                queryVoucher.setOpenEnterprise("腾讯科技有限公司");
            } else if (open.equals("b")) {
                queryVoucher.setOpenEnterprise("隆基股份有限公司");
            } else if (open.equals("c")) {
                queryVoucher.setOpenEnterprise("百度科技有限公司");
            } else if (open.equals("d")) {
                queryVoucher.setOpenEnterprise("京东集团");
            }
        }
        String time = request.getParameter("time");
        if (time != null && !time.isEmpty()) {
            queryVoucher.setOpenTime(time);
        }
        String min = request.getParameter("min");
        System.out.println(min);
        if (min != null && !min.isEmpty()) {
            queryVoucher.setMinAmount(Double.parseDouble(min));
        }
        String max = request.getParameter("max");
        System.out.println(max);
        if (max != null && !max.isEmpty()) {
            queryVoucher.setMaxAmount(Double.parseDouble(max));
        }

        ArrayList<ShowVoucher> vouchers = voucherService.select(queryVoucher);
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(vouchers));
    }
    /**
     * 实现的功能是对于融资列表的全查和精查功能
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void queryDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String no = request.getParameter("no");
        String instituty = request.getParameter("instituty");
        String amout1 = request.getParameter("amout1");
        String amout2 = request.getParameter("amout2");
        String time = request.getParameter("time");
        if (no != null && !no.isEmpty()) {
            financingAnd.setNo(no);
        }
        if (instituty != null && !instituty.isEmpty()) {
            if (instituty.equals("a")) {
                financingAnd.setName("中国工商银行");
            } else if (instituty.equals("b")) {
                financingAnd.setName("中国农业银行");
            } else if (instituty.equals("c")) {
                financingAnd.setName("中国建设银行");
            }
        }
        if (amout1 != null && !amout1.isEmpty()) {
            financingAnd.setMinAmout(Double.parseDouble(amout1));
        }
        if (amout2 != null && !amout2.isEmpty()) {
            financingAnd.setMaxAmout(Double.parseDouble(amout2));
        }
        if (time != null && !time.isEmpty()) {
            financingAnd.setCreate_time(time);
        }
        ArrayList<FinancingAmout> financings = financingService.selectQuery(financingAnd);
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(financings));
    }

    /**
     * 实现的是对于融资列表详情的查询
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void querydetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        FinanceList financeList = financingService.selectByInsitituty_id(Integer.parseInt(request.getParameter("no")));
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(financeList));
    }
    /**
     * 对于按键状态的选择
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @throws ParseException
     */
    public void queryBystatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
        String status = request.getParameter("status");
        if ("A".equals(status)) {
            financingAnd.setStatus("A");
        } else if ("C".equals(status)) {
            financingAnd.setStatus("C");
        } else if ("B".equals(status)) {
            financingAnd.setStatus("B");
        }
        ArrayList financings = financingService.selectQuery(financingAnd);
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(financings));
    }

//    /**
//     * 我的凭证表详情
//     * @param request
//     * @param response
//     * @throws ServletException
//     * @throws IOException
//     */
//    public void querymyticketfinancing(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        MyTicketFinancingVoucherDetail myTicketFinancingVoucherDetail1 = voucherService.selectByVoucherid(Integer.parseInt(request.getParameter("bi")));
//        Gson gson = new Gson();
//        response.getWriter().println(gson.toJson(myTicketFinancingVoucherDetail1));
//    }


    /**
     * 实现功能是登录界面功能
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void queryAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email1 = request.getParameter("email1");
        String password1 = request.getParameter("password1");
        ArrayList<User> users = userService.selectQuery(email1, password1);
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(users.size()));
    }

    /**
     * 我的凭证表详情查询展示输出
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void ticketDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Enumeration<String> parameterNames = request.getParameterNames();
        int voucher_id = Integer.parseInt(request.getParameter("voucher_id"));


        MyTicketDetail voucher = voucherService.selectByVoucher_id(voucher_id);
        System.out.println("验证收到voucher是否发送"+voucher);
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(voucher));

    }

    /**提交融资信息判断是否添加我的凭证表
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void insertFinancing(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        Integer enterprise_id = Integer.parseInt(request.getParameter("id"));//融资企业id
        Double amount = Double.parseDouble(request.getParameter("amount"));//融资金额
        Double voucher_amount = Double.parseDouble(request.getParameter("voucher_amount"));//凭证金额
        Double cost = Double.parseDouble(request.getParameter("cost"));//融资成本
        Double receipt_amount = Double.parseDouble(request.getParameter("receipt_amount"));//预计到账金额
        Integer instituty_id = Integer.parseInt(request.getParameter("instituty_id"));//金融机构id
        Integer receipt_day = Integer.parseInt(request.getParameter("receipt_day"));//预计放款日期天数（int）
        String uplink_address = request.getParameter("uplink_address");//上链地址
        String payment_interest_type = request.getParameter("payment_interest_type");
        String remark = request.getParameter("remark");//备注
        boolean a = false, b = false;
        String no = (UUID.randomUUID().toString().substring(10, 20));
        Financing financing = new Financing();
        financing.setNo(no);
        financing.setEnterprise_id(enterprise_id);
        financing.setInstituty_id(instituty_id);
        financing.setCreate_time(countDate(0));
        financing.setReceipt_time(countDate(receipt_day));
        financing.setUplink_address(uplink_address);
        financing.setStatus("融资中");
        financing.setProgress_status("未放款");
        financing.setPayment_interest_type(payment_interest_type);
        financing.setRemark(remark);
        if (amount == voucher_amount) {
            financing.setAmount(amount);
            financing.setCost(cost);
            financing.setReceipt_amount(receipt_amount);
        } else {
            financing.setAmount(amount);
            financing.setCost(cost * (amount / voucher_amount));
            financing.setReceipt_amount(receipt_amount * (amount / voucher_amount));
            Integer open_enterprise_id = Integer.parseInt(request.getParameter("open_enterprise_id"));
            String expiry_time = request.getParameter("expiry_time");
            String source = request.getParameter("source");
            Voucher voucher = new Voucher();
            no = (UUID.randomUUID().toString().substring(10, 20));
            voucher.setNo(no);
            voucher.setAmount(voucher_amount - amount);
            voucher.setEnterprise_id(enterprise_id);
            voucher.setOpen_enterprise_id(open_enterprise_id);
            voucher.setInstituty_id(instituty_id);
            voucher.setOpen_time(countDate(0));
            voucher.setExpiry_time(expiry_time);
            voucher.setUplink_address(uplink_address);
            voucher.setSource(source);
            voucher.setStatus("已融资");
            if (source.equals("融资留存"))
                voucher.setSource_id(enterprise_id);
            voucher.setPayment_interest_type(payment_interest_type);
            a = voucherService.insertVoucher(voucher);
        }
        b = financingService.insertFinancing(financing);
        if (a == true)
            System.out.println("新建凭证成功");
        if (b == true)
            System.out.println("新建融资成功");
    }

    /**提交内容时间需要判断
     * @param days
     * @return
     */
    public String countDate(int days) {
        SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式化
        Date currentDate = new Date(); // 获取当前日期
        Calendar calendar = Calendar.getInstance(); // 获取日历实例
        calendar.setTime(currentDate); // 设置日历的当前日期
        calendar.add(Calendar.DAY_OF_MONTH, days); // 将日历日期增加指定的天数

        Date newDate = calendar.getTime(); // 获取增加天数后的日期
        String formattedDate = sdFormat.format(newDate); // 格式化日期为字符串
        return formattedDate;
    }


}
